package org.rjxh.examfront.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.rjxh.examfront.mapper.ExamRecordMapper;
import org.rjxh.examfront.pojo.ExamExamination;
import org.rjxh.examfront.mapper.ExamExaminationMapper;
import org.rjxh.examfront.pojo.ExamRecord;
import org.rjxh.examfront.pojo.LoginUser;
import org.rjxh.examfront.pojo.R;
import org.rjxh.examfront.service.IExamExaminationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.rjxh.examfront.web.tools.JwtUtils;
import org.rjxh.examfront.web.tools.RedisCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 考试 服务实现类
 * </p>
 *
 * @author BA7LGJ
 * @since 2024-04-04
 */
@Service
public class ExamExaminationServiceImpl extends ServiceImpl<ExamExaminationMapper, ExamExamination> implements IExamExaminationService {

    @Resource
    private ExamExaminationMapper examExaminationMapper;

    @Resource
    private ExamRecordMapper examRecordMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public R getExaminationListByUserID() {
        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUser().getUserId();
        List<ExamExamination> examinationListByUserID = examExaminationMapper.getExaminationListByUserID(userId);
        return new R(200, examinationListByUserID);
    }

    /**
     * 开始考试请求
     *
     * @param examId
     * @return recordJWT
     */
    @Override
    public R startExam(Long examId) {

        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUser().getUserId();

        ExamExamination examExamination;
        //考试是否开考
        if (Objects.isNull(examExamination = redisCache.getCacheObject("exam:" + examId))) {
            examExamination = examExaminationMapper.selectById(examId);
            if (!examExamination.getStatus().equals("0")) {
                return new R(500, "考试状态异常");
            }
            if (Objects.isNull(examExamination)){
                return new R(500, "考试不存在");
            }
            redisCache.setCacheObject("exam:"+examId, examExamination);
        }

        if (LocalDateTime.now().isBefore(examExamination.getStartTime()) || LocalDateTime.now().isAfter(examExamination.getEndTime())) {
            return new R(500, "考试未开始或已结束");
        }

        //获取 用户考试组ID 如果该id存在则用户可以考
        Long examUserId = examExaminationMapper.selectExamUserId(examId, userId);
        if (Objects.isNull(examUserId)) {
            return new R(500, "错误的请求，该用户无权参与这场考试");
        }

        // 检查用户是否正在考试
        //redisCache.setCacheObject("examRecording:" + recordId, examRecord);
        //redisCache.setCacheObject("examRecordingUser:" + userId, recordId);
        Long examRecording = redisCache.getCacheObject("examRecordingUser:" + userId);
        if (!StringUtils.isEmpty(examRecording)) {
            return new R(200, "您正在考试中");
        }


        //可以考试  创建一个record 记得吧recordId返回
        ExamRecord examRecord = new ExamRecord()
                .setExamUserId(examUserId)
                .setExamStartTime(LocalDateTime.now());
        int insert = examRecordMapper.insert(examRecord);

        if (insert == 0) {
            return new R(500, "考试记录创建失败");
        }

        //创建的recordId，将其返回用户，用户请求答题和结束答题需要用到
        Long recordId = examRecord.getRecordId();

        examRecord.setExamExamination(examExamination);

        redisCache.setCacheObject("examRecording:" + recordId, examRecord);
        redisCache.setCacheObject("examRecordingUser:" + userId, recordId);
        redisCache.setCacheMap("RecordResponds:" + recordId, null);

        return new R(200, "操作成功");
    }

    @Override
    public ExamExamination getExaminationByRecordID(Long recordId) {
        Long examId = examExaminationMapper.selectExamIdByRecordId(recordId);
        return this.getById(examId);
    }


}
